<?php
namespace Home\Controller;
use Think\Controller;

define("TOKEN", "7c32841c18f635e5eed4bcf07afec757");
define("APPID", "wx71bd0c0255c656fe");
define("APPSECRET", "9c8b8c856b7fe4534976655a5de6cca0");
class IndexController extends Controller {
    public function index(){
        $this->responseMsg();
    }
     public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      //extract post data
        if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $type = $postObj->MsgType;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";
                 if($type == "event" && $postObj->Event == 'subscribe'){
                    $msgType = "text";
                    $contentStr = '<a href="http://niap.info/fujie/index.php/home/weixin/index">欢迎关注</a>';//关注公众号时发的内容
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                 }                        
                if($keyword == "你好")//传给公众号的内容
                {
                    $msgType = "text";
                    $contentStr = '<a href="http://www.baidu.com/">点我</a>';//公众号返回的内容
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }
                //if ($keyword == "图文") {
                       /*$articles = array(
                        array(
                            'Title'=> "直播",
                            'Description'=> "直播吧",
                            'PicUrl'=> "http://tu.qiumibao.com/logo/logo_o.jpg",
                            'Url'=> "http://www.zhibo8.cc/",
                            ),array(
                                 'Title'=> "新安",
                                 'Description'=> "新安人才网",
                                 'PicUrl'=> "http://www.goodjobs.cn/images/logo.gif",
                                 'Url'=> "http://www.goodjobs.cn",

                            ));*/
                     $articles = M('articles')->where(array('keyword'=>$keyword))->select();
                     if ($articles) {
                   
                    $textTpl = '<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[news]]></MsgType>
                                <ArticleCount>%s</ArticleCount>
                                <Articles>';
                        foreach ($articles as $a) {
                              $textTpl .= "<item>
                              <Title><![CDATA[".$a['title']."]]></Title>
                              <Description><![CDATA[".$a['description']."]]></Description>
                              <PicUrl><![CDATA[".$a['picurl']."]]></PicUrl>
                              <Url><![CDATA[".$a['url']."]]></Url>
                               </item>";
                           };
                            $textTpl .='</Articles></xml>';
                            $msgType = "news";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,count($articles));
                          echo $resultStr;
                }else{
                  $url="http://www.xiaodoubi.com/simsimiapi.php?msg=".$keyword;
                  $response=http_get($url);
                  $msgType = "text";
                  $contentStr ='<a href="http://niap.info/fujie/index.php/home/weixin/index">欢迎关注</a>';//关注时返回
                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                 echo $resultStr;
                  }
                  //}
                


        }else {
            echo "";
            exit;
        }
    }
  
    public function creatMenu(){
     $access_token = $this->getAccessToken();
     $url =  "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=". $access_token;
      /*$data = '{
           "button":[
           {  
                "type":"click",
                "name":"今日歌曲",
                "key":"V1001_TODAY_MUSIC"
            },
            {
                 "name":"菜单",
                 "sub_button":[
                 {  
                     "type":"view",
                     "name":"搜索",
                     "url":"http://www.soso.com/"
                  },
                  {
                     "type":"view",
                     "name":"视频",
                     "url":"http://v.qq.com/"
                  },
                  {
                     "type":"click",
                     "name":"赞一下我们",
                     "key":"V1001_GOOD"
                  }]
             }]
       }';*/
     $data = array(
           'button'=>array(
            array(
             'type'=>"click",
             'name'=>"今日歌曲",
             'key'=>"V1001_TODAY_MUSIC",
             ),
            array(
             'name'=>"菜单",
             'sub_button'=>array(
                   array(
                 'type'=>"view",
                 'name'=>"搜索",
                 'url'=>"http://www.soso.com/",
                  ),array(
                  'type'=>"view",
                  'name'=>"视频",
                  'url'=>"http://v.qq.com/",
                  ),array(
                   'type'=>"click",
                  'name'=>"赞一下我们",
                  'key'=>"V1001_GOOD",
                   )))));
       $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        var_dump(http_post($url,$data)) ;
    }
    public function text(){
      $keyword = "图文";
      $articles = M('articles')->where(array('keyword'=>$keyword))->select();
      var_dump($articles); 
    }

     private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}